package com.aco.party.web.controller.system;

import com.aco.party.util.PathUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.aco.party.util.WebModelUtil.getImgPath;

/**
 * Created by WangShijun on 2016/3/8.
 */
@Controller
@RequestMapping("/system")
public class UploadifyImageUpController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(UploadifyImageUpController.class);

    @ResponseBody
    @RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
    public String upload(DefaultMultipartHttpServletRequest request){
        Map map = new HashMap();
        try {
            //可以上传多个文件
            List<MultipartFile> files = request.getMultiFileMap().get("file");
            if(files != null ) {
                for (MultipartFile item : files) {
                    if (!item.isEmpty()) {
                        String name = item.getOriginalFilename();
                        String fileSuffix = PathUtil.getExtension(name);
                        String oldName = name.replaceAll(fileSuffix, "");
                        String fileName = UUID.randomUUID().toString();
                        String newName = fileName + fileSuffix;
                        String parentPath = getImgPath();
                        logger.info("parentPath:" + parentPath);
                        FileOutputStream out = new FileOutputStream(parentPath + newName);
                        FileInputStream in = (FileInputStream)item.getInputStream();
                        operateByNio(in,out);
                        /**将上传处理后的数据返回**/
                        map.put("fileSuffix", fileSuffix);
                        map.put("fileName", oldName);
                        map.put("filePath", newName);
                        break;
                    }
                }
            }
        }catch (Exception e) {
            logger.error("上传图片失败！e:" + e.getMessage());
            logger.error(e.getCause().toString());
        }
        JSONObject jsonObject = JSONObject.fromObject(map);
        String msg =  jsonObject.toString();
        logger.info("上传图片返回：" + msg);
        return msg;
    }

    private void operateByNio(FileInputStream inputStream,FileOutputStream outputStream) throws Exception{

        FileChannel inChannel = inputStream.getChannel(); //获取输入通道
        FileChannel outChannel = outputStream.getChannel(); //获取输出通道

        ByteBuffer mByteBuffer = ByteBuffer.allocate(1024); //分配缓冲区大小

        while (true) {

            mByteBuffer.clear(); //清除操作:将position设置为0，limit(限制)设置为capasity(容量)的大小

            int r = inChannel.read(mByteBuffer); //将字节流从该通道读入缓冲区

            //r=-1时代表已经到达流的末尾
            if (r == -1) {
                break;
            }

            mByteBuffer.flip(); //反转操作:将limit设置为当前的position，再将position设置为0

            outChannel.write(mByteBuffer); //将缓冲区中字节流写入该通道

        }

        inChannel.close();
        outChannel.close();
        inputStream.close();
        outputStream.close();
    }
}
